<!DOCTYPE html>
<html lang="zh-CN">
{% load static %}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标签管理 - IP区域查询系统</title>
    <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">
    <script src="{% static 'jquery/jquery.min.js' %}"></script>
    <script src="{% static 'bootstrap/js/bootstrap.bundle.min.js' %}"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f8f9fa;
        }
        .header {
            background-color: #343a40;
            color: white;
            padding: 1rem;
            margin-bottom: 2rem;
        }
        .card {
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 1rem;
        }
        .badge-active {
            background-color: #28a745;
        }
        .badge-inactive {
            background-color: #dc3545;
        }
        .action-buttons .btn {
            margin-right: 0.5rem;
            margin-bottom: 0.5rem;
        }
        .form-control:focus {
            border-color: #495057;
            box-shadow: 0 0 0 0.2rem rgba(73, 80, 87, 0.25);
        }
        .checkbox-column {
            width: 40px;
        }
        .status-column {
            width: 120px;
        }
        .action-column {
            width: 180px;
        }
        .pagination {
            margin-top: 1rem;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="container">
            <h1>标签管理</h1>
            <p>管理系统中的标签数据</p>
        </div>
    </div>

    <div class="container">
        <!-- 工具栏 -->
        <div class="card">
            <div class="card-body">
                <div class="row mb-4">
                    <div class="col-md-6">
                        <button id="addTagBtn" class="btn btn-primary">
                            <i class="bi bi-plus-circle"></i> 新增标签
                        </button>
                        <button id="batchDeleteBtn" class="btn btn-danger ml-2" disabled>
                            <i class="bi bi-trash"></i> 批量删除
                        </button>
                        <button id="batchActivateBtn" class="btn btn-success ml-2" disabled>
                            <i class="bi bi-check-circle"></i> 批量启用
                        </button>
                        <button id="batchDeactivateBtn" class="btn btn-warning ml-2" disabled>
                            <i class="bi bi-x-circle"></i> 批量禁用
                        </button>
                    </div>
                    <div class="col-md-6">
                        <form id="searchForm" class="form-inline justify-content-end">
                            <div class="form-group mr-2">
                                <input type="text" name="name" class="form-control" placeholder="标签名称" value="{{ name }}">
                            </div>
                            <div class="form-group mr-2">
                                <select name="is_active" class="form-control">
                                    <option value="">全部状态</option>
                                    <option value="true" {% if is_active == "true" %}selected{% endif %}>启用</option>
                                    <option value="false" {% if is_active == "false" %}selected{% endif %}>禁用</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-outline-secondary">搜索</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 标签列表 -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th class="checkbox-column">
                                    <input type="checkbox" id="selectAll">
                                </th>
                                <th>ID</th>
                                <th>标签名称</th>
                                <th>描述</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>创建者</th>
                                <th>使用次数</th>
                                <th class="action-column">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for tag in tags %}
                            <tr>
                                <td>
                                    <input type="checkbox" class="tag-checkbox" value="{{ tag.id }}">
                                </td>
                                <td>{{ tag.id }}</td>
                                <td>{{ tag.name }}</td>
                                <td>{{ tag.description|default:"-" }}</td>
                                <td>
                                    <span class="badge {% if tag.is_active %}badge-active{% else %}badge-inactive{% endif %}">
                                        {{ tag.is_active|yesno:"启用,禁用" }}
                                    </span>
                                </td>
                                <td>{{ tag.created_at|date:"Y-m-d H:i:s" }}</td>
                                <td>{{ tag.created_by.username|default:"-" }}</td>
                                <td>{{ tag.usage_count }}</td>
                                <td class="action-buttons">
                                    <button class="btn btn-sm btn-outline-primary edit-btn" data-id="{{ tag.id }}">
                                        编辑
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger delete-btn" data-id="{{ tag.id }}">
                                        删除
                                    </button>
                                </td>
                            </tr>
                            {% empty %}
                            <tr>
                                <td colspan="9" class="text-center">暂无数据</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-inline">
                            <label for="per_page" class="mr-2">每页显示：</label>
                            <select id="per_page" class="form-control" style="width: auto;">
                                <option value="10" {% if per_page == '10' %}selected{% endif %}>10条</option>
                                <option value="20" {% if per_page == '20' %}selected{% endif %}>20条</option>
                                <option value="50" {% if per_page == '50' %}selected{% endif %}>50条</option>
                                <option value="100" {% if per_page == '100' %}selected{% endif %}>100条</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <nav aria-label="Page navigation">
                            <ul class="pagination">
                                {% if tags.has_previous %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ tags.previous_page_number }}{% if name %}&name={{ name }}{% endif %}{% if is_active %}&is_active={{ is_active }}{% endif %}{% if per_page %}&per_page={{ per_page }}{% endif %}" aria-label="Previous">
                                        <span aria-hidden="true">&laquo;</span>
                                    </a>
                                </li>
                                {% endif %}
                                {% for num in tags.paginator.page_range %}
                                {% if tags.number == num %}
                                <li class="page-item active"><a class="page-link" href="#">{{ num }}</a></li>
                                {% else %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ num }}{% if name %}&name={{ name }}{% endif %}{% if is_active %}&is_active={{ is_active }}{% endif %}{% if per_page %}&per_page={{ per_page }}{% endif %}">{{ num }}</a>
                                </li>
                                {% endif %}
                                {% endfor %}
                                {% if tags.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ tags.next_page_number }}{% if name %}&name={{ name }}{% endif %}{% if is_active %}&is_active={{ is_active }}{% endif %}{% if per_page %}&per_page={{ per_page }}{% endif %}" aria-label="Next">
                                        <span aria-hidden="true">&raquo;</span>
                                    </a>
                                </li>
                                {% endif %}
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增/编辑标签模态框 -->
    <div class="modal fade" id="tagModal" tabindex="-1" aria-labelledby="tagModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="tagModalLabel">新增标签</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="tagForm">
                        <input type="hidden" id="tagId">
                        <div class="mb-3">
                            <label for="tagName" class="form-label">标签名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="tagName" required maxlength="50">
                            <div class="invalid-feedback"></div>
                        </div>
                        <div class="mb-3">
                            <label for="tagDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="tagDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="tagIsActive" checked>
                            <label class="form-check-label" for="tagIsActive">启用</label>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="saveTagBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 全选/取消全选
            $('#selectAll').change(function() {
                $('.tag-checkbox').prop('checked', $(this).prop('checked'));
                updateBatchButtonStates();
            });

            // 单个复选框改变
            $('.tag-checkbox').change(function() {
                updateBatchButtonStates();
            });

            // 更新批量操作按钮状态
            function updateBatchButtonStates() {
                const checkedCount = $('.tag-checkbox:checked').length;
                $('#batchDeleteBtn, #batchActivateBtn, #batchDeactivateBtn').prop('disabled', checkedCount === 0);
            }

            // 每页显示条数改变
            $('#per_page').change(function() {
                const form = $('#searchForm');
                const action = form.attr('action') || window.location.pathname;
                const queryParams = new URLSearchParams(window.location.search);
                queryParams.set('per_page', $(this).val());
                queryParams.set('page', 1);
                window.location.href = `${action}?${queryParams.toString()}`;
            });

            // 新增标签
            $('#addTagBtn').click(function() {
                $('#tagModalLabel').text('新增标签');
                $('#tagId').val('');
                $('#tagForm')[0].reset();
                $('#tagModal').modal('show');
            });

            // 编辑标签
            $('.edit-btn').click(function() {
                const tagId = $(this).data('id');
                // 这里应该通过AJAX获取标签数据
                // 为了演示，我们直接从DOM中获取
                const row = $(this).closest('tr');
                const name = row.find('td:eq(2)').text();
                const description = row.find('td:eq(3)').text() === '-' ? '' : row.find('td:eq(3)').text();
                const isActive = row.find('td:eq(4) .badge').hasClass('badge-active');

                $('#tagModalLabel').text('编辑标签');
                $('#tagId').val(tagId);
                $('#tagName').val(name);
                $('#tagDescription').val(description);
                $('#tagIsActive').prop('checked', isActive);
                $('#tagModal').modal('show');
            });

            // 保存标签
            $('#saveTagBtn').click(function() {
                const tagId = $('#tagId').val();
                const name = $('#tagName').val().trim();
                const description = $('#tagDescription').val().trim();
                const isActive = $('#tagIsActive').prop('checked');

                // 前端验证
                if (!name) {
                    $('#tagName').addClass('is-invalid');
                    $('#tagName').next('.invalid-feedback').text('标签名称不能为空');
                    return;
                } else {
                    $('#tagName').removeClass('is-invalid');
                }

                const url = tagId ? `/tags/update/${tagId}/` : '/tags/create/';
                const method = 'POST';
                const data = JSON.stringify({ name, description, is_active: isActive });

                $.ajax({
                    url: url,
                    method: method,
                    contentType: 'application/json',
                    data: data,
                    success: function(response) {
                        if (response.status === 'success') {
                            alert(response.message);
                            location.reload();
                        } else {
                            alert('错误：' + response.message);
                        }
                    },
                    error: function(xhr) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            alert('错误：' + response.message);
                        } catch (e) {
                            alert('保存失败，请稍后重试');
                        }
                    }
                });
            });

            // 删除标签
            $('.delete-btn').click(function() {
                const tagId = $(this).data('id');
                if (confirm('确定要删除这个标签吗？')) {
                    $.ajax({
                        url: `/tags/delete/${tagId}/`,
                        method: 'POST',
                        success: function(response) {
                            if (response.status === 'success') {
                                alert(response.message);
                                location.reload();
                            } else {
                                alert('错误：' + response.message);
                            }
                        },
                        error: function() {
                            alert('删除失败，请稍后重试');
                        }
                    });
                }
            });

            // 批量操作
            $('#batchDeleteBtn').click(function() {
                const tagIds = $('.tag-checkbox:checked').map(function() { return $(this).val(); }).get();
                if (confirm(`确定要删除选中的 ${tagIds.length} 个标签吗？`)) {
                    performBatchAction(tagIds, 'delete');
                }
            });

            $('#batchActivateBtn').click(function() {
                const tagIds = $('.tag-checkbox:checked').map(function() { return $(this).val(); }).get();
                performBatchAction(tagIds, 'activate');
            });

            $('#batchDeactivateBtn').click(function() {
                const tagIds = $('.tag-checkbox:checked').map(function() { return $(this).val(); }).get();
                performBatchAction(tagIds, 'deactivate');
            });

            function performBatchAction(tagIds, action) {
                $.ajax({
                    url: '/tags/batch-action/',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ tag_ids: tagIds, action: action }),
                    success: function(response) {
                        if (response.status === 'success') {
                            alert(response.message);
                            location.reload();
                        } else {
                            alert('错误：' + response.message);
                        }
                    },
                    error: function() {
                        alert('操作失败，请稍后重试');
                    }
                });
            }
        });
    </script>
</body>
</html>
